import Link from "next/link";
import Image from "next/image";
import { useState } from "react";
import { VideoItem } from "../types/video";
import { VideoApiService } from "../lib/api-client";

function formatDuration(seconds: number) {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  if (h > 0) return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
  return `${m}:${String(s).padStart(2, "0")}`;
}

interface VideoCardProps {
  video: VideoItem;
  refreshVideos: () => void;
}

export default function VideoCard({ video, refreshVideos }: VideoCardProps) {
  const defaultCoverUrl = "https://n.sinaimg.cn/sinacn10113/332/w1024h1708/20190806/3afd-iatixpm8624881.jpg";
  const [isDeleting, setIsDeleting] = useState(false);
  video.averageRating = Number(video.averageRating) || 0;
  const handleDelete = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();

    if (!confirm(`确定要删除视频"${video.id}"吗？此操作不可恢复。`)) {
      return;
    }

    setIsDeleting(true);
    try {
      const response = await VideoApiService.deleteVideo(video.id);
      if (response.success) {
        if (refreshVideos) {
          refreshVideos();
        }
        // alert('视频删除成功');
      } else {
        alert(`删除失败: ${response.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('删除视频失败:', error);
      alert('删除失败，请稍后重试');
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <div className="relative group block overflow-hidden rounded-lg border border-zinc-200 bg-white shadow-sm transition hover:-translate-y-0.5 hover:shadow-md dark:border-zinc-800 dark:bg-zinc-950">
      {/* 删除按钮 - 只在有onDelete回调时显示 */}

      <Link
        href={`/watch/${video.id}`}
        className="block"
      >
        <div className="relative aspect-video w-full">
          <Image
            src={video.coverUrl || defaultCoverUrl}
            alt={video.title}
            fill
            sizes="(max-width: 768px) 100vw, 33vw"
            className="object-cover"
          />
          <span className="absolute bottom-2 right-2 rounded bg-black/70 px-1.5 py-0.5 text-xs text-white">
            {formatDuration(video.durationSeconds)}
          </span>
        </div>
        <div className="space-y-1 p-3">
          <h3 className="line-clamp-2 text-sm font-medium text-zinc-900 group-hover:text-zinc-700 dark:text-zinc-100 dark:group-hover:text-zinc-300">
            {video.title}
          </h3>
          <div className="text-xs text-zinc-500 dark:text-zinc-400">{video.category}</div>
          {/* 显示评分信息 */}
          {video.averageRating && video.averageRating > 0 && (
            <div className="flex items-center space-x-1">
              <svg 
                xmlns="http://www.w3.org/2000/svg" 
                width="12" 
                height="12" 
                viewBox="0 0 24 24" 
                fill="currentColor" 
                stroke="currentColor" 
                strokeWidth="2" 
                strokeLinecap="round" 
                strokeLinejoin="round"
                className="text-yellow-400"
              >
                <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
              </svg>
              <span className="text-xs text-zinc-700 dark:text-zinc-300">
                {video.averageRating.toFixed(1)} ({video.ratingCount || 0})
              </span>
            </div>
          )}
        </div>
      </Link>
      <button
        onClick={handleDelete}
        disabled={isDeleting}
        className="absolute bottom-2 right-2 rounded-full bg-red-500/90 p-1.5 text-white opacity-0 transition-opacity hover:bg-red-600 dark:opacity-0 group-hover:opacity-100"
        aria-label="删除视频"
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>
    </div>
  );
}


